package cn.edu.stu.syllabus.repository.oa.remote;

import java.util.List;

import cn.edu.stu.syllabus.api.OaInfoApi;
import cn.edu.stu.syllabus.repository.oa.OaDataSource;
import cn.edu.stu.syllabus.repository.oa.OaInfoConverter;
import cn.edu.stu.syllabus.repository.oa.OaSearchInfo;
import cn.edu.stu.syllabus.repository.oa.local.OaInfoEntry;
import rx.Observable;
import rx.functions.Func1;

/**
 * Created by daidaijie on 2017/3/14.
 */

public class OaRemoteDataSource implements OaDataSource {

    private OaInfoApi mOaInfoApi;

    public OaRemoteDataSource(OaInfoApi oaInfoApi) {
        mOaInfoApi = oaInfoApi;
    }

    @Override
    public Observable<List<OaInfoEntry>> getOaInfoEntries(OaSearchInfo oaSearchInfo, int start, int end) {

        return mOaInfoApi.getOAInfo("undefined",
                oaSearchInfo.getSubCompanyId(), oaSearchInfo.getKeyword(),
                start, end)
                .flatMap(new Func1<List<OaInfo>, Observable<OaInfo>>() {
                    @Override
                    public Observable<OaInfo> call(List<OaInfo> oaInfos) {
                        return Observable.from(oaInfos);
                    }
                })
                .filter(new Func1<OaInfo, Boolean>() {
                    @Override
                    public Boolean call(OaInfo oaInfo) {
                        return oaInfo.getDOCVALIDDATE() != null &&
                                oaInfo.getDOCVALIDTIME() != null;
                    }
                })
                .map(new Func1<OaInfo, OaInfoEntry>() {
                    @Override
                    public OaInfoEntry call(OaInfo oaInfo) {
                        return OaInfoConverter.convert(oaInfo);
                    }
                })
                .toList();
    }

    @Override
    public boolean isSourceEmpty(Throwable errMsg) {
        String errMsgClassName = errMsg.getClass().getSimpleName();
        return errMsgClassName.equals("EOFException")
                || errMsgClassName.equals("MalformedJsonException");
    }


}
